using System.Net;

namespace GossipCore;

public class ArgsParser
{
    public static (string id, IDictionary<string, IPEndPoint> peers) ParseArgs(string[] args)
    {
        string id = null;
        string peersArg = null;
        foreach (var arg in args)
        {
            if (arg.StartsWith("--id="))
                id = arg.Substring("--id=".Length);
            else if (arg.StartsWith("--peers="))
                peersArg = arg.Substring("--peers=".Length);
        }
        var peers = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
        if (!string.IsNullOrWhiteSpace(peersArg))
        {
            foreach (var entry in peersArg.Split(',', StringSplitOptions.RemoveEmptyEntries))
            {
                var parts = entry.Split('@');
                if (parts.Length == 2)
                    peers[parts[0]] = parts[1];
            }
        }
        var ipDict = ConvertToIPEndPoints(peers);
        return (id, new Dictionary<string, IPEndPoint>(ipDict));
    }
    public static IDictionary<string, IPEndPoint> ConvertToIPEndPoints(IDictionary<string, string> peers)
    {
        var ipDict = new Dictionary<string, IPEndPoint>();
        foreach (var kv in peers)
        {
            var parts = kv.Value.Split(':');
            ipDict[kv.Key] = new IPEndPoint(IPAddress.Parse(parts[0]), int.Parse(parts[1]));
        }
        return ipDict;
    }
}